using System;
using System.Linq;
using NHibernate.Event;
using Caramel.Entities;

namespace Caramel.NHibernate.Entities
{
	public class PreInsertEntityEventListener : IPreInsertEventListener
	{
		#region IPreInsertEventListener Members

		public virtual bool OnPreInsert(PreInsertEvent @event)
		{
			var immutable = @event.Entity as IImmutable;

			if (immutable == null)
			{
				return false;
			}

			var created = SystemTime.Now;
			var createdBy = CurrentUser.Name;

			if (@event.Persister.PropertyNames.Contains("Created"))
			{
				@event.State[Array.IndexOf(@event.Persister.PropertyNames, "Created")] = created;
			}

			if (@event.Persister.PropertyNames.Contains("CreatedBy"))
			{
				@event.State[Array.IndexOf(@event.Persister.PropertyNames, "CreatedBy")] = createdBy;
			}

			immutable.Created = created;
			immutable.CreatedBy = createdBy;

			return false;
		}

		#endregion
	}
}
